package com.dayu.finecomm.dsc.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

import com.dayu.finecomm.dsc.DSCInterface;
import com.dayu.finecomm.dsc.DTUProxyManager;
import com.dayu.finecomm.dsc.net.DSCNetManager;
import com.dayu.finecomm.dsc.protocol.DDP;
import com.dayu.finecomm.dsc.protocol.DDP.DDPPack;

/**
 * 处理来自Tcp的消息
 * 
 * @author hddz
 * @since 2017-07-27 15:48:20
 * @version V1.0
 */
public class DSCTcpHandler extends DSCHandler<ByteBuf> {
	/**
	 * DDP协议解析器
	 */
	private DDP mDDP = null;

	public DSCTcpHandler(DSCInterface callback) {
		mDDP = new DDP();
		mCallback = callback;
	}

	/**
	 * 处理接收消息
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf)
			throws Exception {
		String socket = getRemoteAddress(ctx);

		byte[] msg = new byte[buf.readableBytes()];
		buf.readBytes(msg);

		DDPPack pack = mDDP.unpack(msg);
		DDPPack ackPack = DTUProxyManager.getInstance().processDDP(socket,
				ctx.channel(), DSCNetManager.DSC_NET_TCP, pack);

		if (null != ackPack) {
			byte[] byteAck = mDDP.pack(ackPack, DDP.DDP_UDP);
			ByteBuf bufAck = Unpooled.buffer(byteAck.length);
			bufAck.writeBytes(byteAck);
			ctx.writeAndFlush(bufAck);

			if (DDP.DTU_PACK_TYPE_REG == pack.getType()) {
				ctx.fireChannelActive();
			}
		} else {
			if (DDP.DTU_PACK_TYPE_SEND_DATA == pack.getType()) {
				ByteBuf userBuf = Unpooled.buffer(msg.length);
				userBuf.writeBytes(msg);

				ctx.fireChannelRead(userBuf);
			}
		}
	}
}
